<template>
  <div class="html-formatter">
    <button @click="returnFn" class="btn btn-primary retrunBUtton">
      <i class="icon">⚡</i> 返回
    </button>
    <div class="container">
      <header class="tool-header">
        <h1>HTML 格式化工具</h1>
        <p class="subtitle">使用Vue 3实现的HTML代码美化工具</p>
      </header>

      <div class="tool-content">
        <div class="editor-section">
          <div class="input-panel">
            <div class="panel-header">
              <label for="htmlInput">输入HTML代码：</label>
              <div class="action-buttons">
                <button class="format-btn" @click="formatHTML" :disabled="!inputHTML">
                  {{ isFormatted ? '重新格式化' : '格式化代码' }}
                </button>
                <button class="clear-btn" @click="clearInput">清空</button>
              </div>
            </div>
            <textarea
              id="htmlInput"
              v-model="inputHTML"
              placeholder="粘贴HTML代码到这里..."
              rows="15"
              :class="{ formatted: isFormatted }"
            ></textarea>
          </div>

          <div class="output-panel">
            <div class="panel-header">
              <label>格式化结果：</label>
              <div class="action-buttons">
                <button class="copy-btn" @click="copyOutput" :disabled="!formattedHTML">
                  {{ copyButtonText }}
                </button>
              </div>
            </div>
            <pre
              class="formatted-code"
            ><code>{{ formattedHTML || '格式化后的HTML将显示在这里' }}</code></pre>
          </div>
        </div>

        <div class="options-section">
          <h3>格式化选项</h3>
          <div class="options-grid">
            <div class="option-item">
              <label class="checkbox-label">
                <input type="checkbox" v-model="options.indentWithTabs" />
                <span class="checkmark"></span>
                使用制表符缩进
              </label>
            </div>
            <div class="option-item">
              <label class="checkbox-label">
                <input type="checkbox" v-model="options.wrapAttributes" />
                <span class="checkmark"></span>
                属性换行显示
              </label>
            </div>
            <div class="option-item">
              <label>缩进大小：</label>
              <select v-model="options.indentSize">
                <option value="2">2 空格</option>
                <option value="4">4 空格</option>
                <option value="8">8 空格</option>
              </select>
            </div>
            <div class="option-item">
              <label>最大属性长度：</label>
              <input type="number" v-model="options.maxAttributeLength" min="1" max="100" />
            </div>
          </div>
        </div>

        <div class="info-section">
          <h3>关于HTML格式化</h3>
          <p>
            HTML格式化工具可以帮助您整理和美化HTML代码，使其具有一致的缩进和结构，提高代码的可读性和可维护性。格式化后的代码更易于阅读、调试和协作。
          </p>
        </div>
      </div>

      <footer class="tool-footer">
        <p>© 2023 Vue 3 HTML格式化工具</p>
      </footer>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
const inputHTML = ref('')
const formattedHTML = ref('')
const isFormatted = ref(false)
const copyButtonText = ref('复制代码')
const Router = useRouter()
// 格式化选项
const options = ref({
  indentWithTabs: false,
  wrapAttributes: false,
  indentSize: 2,
  maxAttributeLength: 40
})


const returnFn = () => {
  Router.go(-1)
}
// HTML格式化函数
const formatHTML = () => {
  if (!inputHTML.value.trim()) {
    formattedHTML.value = ''
    isFormatted.value = false
    return
  }

  try {
    let html = inputHTML.value
    let indentLevel = 0
    const indentChar = options.value.indentWithTabs ? '\t' : ' '.repeat(parseInt(options.value.indentSize))
    const tokens = html.split(/(<[^>]*>)/g)
    let result = []
    let inTag = false
    let currentTag = ''

    tokens.forEach(token => {
      if (token === '') return

      if (token.startsWith('</')) {
        // 结束标签
        indentLevel = Math.max(0, indentLevel - 1)
        result.push(indentChar.repeat(indentLevel) + token)
      } else if (token.startsWith('<') && !token.startsWith('<!--') && !token.startsWith('<!')) {
        // 开始标签或自闭合标签
        if (!token.endsWith('/>') && !token.startsWith('<?') && !token.startsWith('<%')) {
          // 不是自闭合标签
          inTag = true
          currentTag = token

          // 处理属性换行
          if (options.value.wrapAttributes && token.length > options.value.maxAttributeLength) {
            const tagNameMatch = token.match(/^<(\w+)/)
            if (tagNameMatch) {
              const tagName = tagNameMatch[1]
              const attributes = token.slice(tagName.length + 1, -1).trim()

              if (attributes) {
                const formattedTag = `\n${indentChar.repeat(indentLevel + 1)}<${tagName}\n${indentChar.repeat(indentLevel + 2)}${attributes.split(/\s+/).join(`\n${indentChar.repeat(indentLevel + 2)}`)}\n${indentChar.repeat(indentLevel + 1)}>`
                result.push(formattedTag)
                indentLevel++
                inTag = false
                return
              }
            }
          }

          result.push(indentChar.repeat(indentLevel) + token)
          indentLevel++
        } else {
          // 自闭合标签
          result.push(indentChar.repeat(indentLevel) + token)
        }
      } else if (token.startsWith('<!--') || token.startsWith('<!') || token.startsWith('<%') || token.startsWith('<?')) {
        // 注释或特殊标签
        result.push(indentChar.repeat(indentLevel) + token)
      } else {
        // 文本内容
        if (token.trim()) {
          const lines = token.split('\n')
          lines.forEach((line, index) => {
            if (line.trim()) {
              result.push(indentChar.repeat(inTag ? indentLevel : Math.max(0, indentLevel - 1)) + line.trim())
            }
          })
        }
      }
    })

    formattedHTML.value = result.filter(line => line.trim()).join('\n')
    isFormatted.value = true
  } catch (error) {
    console.error('格式化错误:', error)
    formattedHTML.value = '格式化出错，请检查HTML代码语法'
    isFormatted.value = false
  }
}

// 监听输入变化
watch(inputHTML, (newValue) => {
  if (newValue && isFormatted.value) {
    isFormatted.value = false
  }
})

// 监听选项变化，重新格式化
watch(options, () => {
  if (inputHTML.value && isFormatted.value) {
    formatHTML()
  }
}, { deep: true })

// 复制到剪贴板
const copyOutput = async () => {
  if (!formattedHTML.value) return

  try {
    await navigator.clipboard.writeText(formattedHTML.value)
    copyButtonText.value = '已复制!'
    setTimeout(() => {
      copyButtonText.value = '复制代码'
    }, 2000)
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = formattedHTML.value
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      copyButtonText.value = '已复制!'
      setTimeout(() => {
        copyButtonText.value = '复制代码'
      }, 2000)
    } catch (err2) {
      copyButtonText.value = '复制失败'
      setTimeout(() => {
        copyButtonText.value = '复制代码'
      }, 2000)
    }
    document.body.removeChild(textArea)
  }
}

// 清空输入
const clearInput = () => {
  inputHTML.value = ''
  formattedHTML.value = ''
  isFormatted.value = false
}
</script>

<style scoped>
.btn {
  padding: 8px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: linear-gradient(to right, #1a2a6c, #b21f1f);
  color: white;
}
.retrunBUtton {
  position: absolute;
  top: 100px;
  right: 100px;
}
.html-formatter {
  position: relative;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.container {
  width: 100%;
  max-width: 1400px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.tool-header {
  background: linear-gradient(to right, #667eea, #764ba2);
  color: white;
  padding: 25px 30px;
  text-align: center;
}

.tool-header h1 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.subtitle {
  font-size: 16px;
  opacity: 0.9;
}

.tool-content {
  padding: 30px;
}

.editor-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.input-panel,
.output-panel {
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.panel-header label {
  font-weight: 600;
  color: #333;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.format-btn,
.clear-btn,
.copy-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.format-btn {
  background: linear-gradient(to right, #4caf50, #45a049);
  color: white;
}

.format-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3);
}

.format-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.clear-btn {
  background: #ff9800;
  color: white;
}

.clear-btn:hover {
  background: #f57c00;
  transform: translateY(-2px);
}

.copy-btn {
  background: #2196f3;
  color: white;
}

.copy-btn:hover:not(:disabled) {
  background: #1976d2;
  transform: translateY(-2px);
}

.copy-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

textarea {
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  font-family: 'Courier New', monospace;
  resize: vertical;
  transition: border-color 0.3s;
  background: #f8f9fa;
  height: 300px;
}

textarea:focus {
  outline: none;
  border-color: #667eea;
}

textarea.formatted {
  border-color: #4caf50;
}

.formatted-code {
  height: 300px;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  background: #2d3748;
  color: #e2e8f0;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  overflow: auto;
  white-space: pre-wrap;
  line-height: 1.5;
  margin-top: 0;
}

.options-section {
  margin-bottom: 30px;
}

.options-section h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
}

.option-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item label {
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  font-weight: normal !important;
}

.checkbox-label input {
  display: none;
}

.checkmark {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 4px;
  position: relative;
  transition: all 0.3s;
}

.checkbox-label input:checked + .checkmark {
  background: #667eea;
  border-color: #667eea;
}

.checkbox-label input:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  color: white;
  font-size: 14px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

select,
input[type='number'] {
  padding: 8px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
}

select:focus,
input[type='number']:focus {
  outline: none;
  border-color: #667eea;
}

.info-section {
  background-color: #e3f2fd;
  border-left: 4px solid #2196f3;
  padding: 15px;
  border-radius: 0 8px 8px 0;
}

.info-section h3 {
  color: #1565c0;
  margin-bottom: 10px;
  font-size: 18px;
}

.info-section p {
  color: #424242;
  line-height: 1.6;
  font-size: 14px;
  margin: 0;
}

.tool-footer {
  text-align: center;
  padding: 20px;
  color: #757575;
  font-size: 14px;
  border-top: 1px solid #e0e0e0;
}

@media (max-width: 768px) {
  .editor-section {
    grid-template-columns: 1fr;
  }

  .options-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>